package com.fast.fastenjoy.base.web.action;

import java.awt.image.RenderedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.fast.fastenjoy.base.web.binding.DateConvertEditor;
import com.fast.fastenjoy.base.web.utils.ActionContext;

/**
 * 前端父类控制器
 * @author chenliaohua
 *
 */
@Controller
@RequestMapping("/baseAction")
public class BaseAction implements Serializable{
	
	private static final long serialVersionUID = -1872559020319730427L;
	
	public static final String IMG_TYPE_JPEG = "JPEG";

	@InitBinder
	public void initBinder(ServletRequestDataBinder binder) {
		binder.registerCustomEditor(Date.class, new DateConvertEditor());
	}
	
	protected ActionContext getActionContext(){
		
		return ActionContext.getActionContext();
	}
	
	protected HttpServletResponse getResponse() {
		
		return getActionContext().getResponse();
	}
	
	public HttpServletRequest getRequest(){
		
		return getActionContext().getRequest();
	}
	
	public String getParameter(String name){
		
		return getRequest().getParameter(name);
	}
	
	public BaseAction setAttribute(String name, Object value){
		getRequest().setAttribute(name, value);
		return this;
	}
	
	protected void toRenderedImage(String imageType, RenderedImage renderedImage){
		
		HttpServletResponse response = getResponse();
		
		try {
			ImageIO.write(renderedImage, imageType, response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	protected void toRenderedImage(RenderedImage renderedImage){
		
		toRenderedImage(IMG_TYPE_JPEG, renderedImage);
	}
	
	protected void toHtml(String html){
		try {
			HttpServletResponse response = getResponse();
			response.setContentType("application/html");
			response.setHeader("Cache-Control", "no-store");
			PrintWriter writer = response.getWriter();
			writer.print(html);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	protected void toJson(Object obj){
		try {
			String json = JSONObject.toJSONString(obj);
		
			HttpServletResponse response = getResponse();
		
			response.setContentType("application/json");
			response.setHeader("Cache-Control", "no-store");
		
			PrintWriter writer = response.getWriter();
			writer.print(json);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
